<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            font-size: 14px;
        }

        .flex-start-center {
            display: flex;
            align-items: center;
        }

        .margin-left-5 {
            margin-left: 5px;
        }

        .flex-1 {
            flex: 1;
        }

        .input {
            height: 60px;
        }

        button {
            background-color: #6496c8;
            border: none;
            color: white;
            /*padding: 15px 32px;*/
            height: 65.97px;
            width: 100px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
        }

        button:hover {
            cursor: pointer;
        }
    </style>
</head>
<body>
<ul id="ul"></ul>
<div class="flex-start-center">
    <textarea class="flex-1 input" id="input" placeholder="请输入消息"></textarea>
    <button id="btn">发送</button>
</div>
<div>
    <input type="file" id="file">
</div>
<script>
    ;(function() {
        const domInput = document.querySelector('#input');
        const domBtn = document.querySelector('#btn');
        const domUl = document.getElementById('ul');
        const domFile = document.getElementById('file');
        const username = localStorage.getItem('username');
        const ws = new WebSocket(`ws://${location.hostname}:8886`);

        function init() {
            if (!username) {
                location.href = './entry.html';
            }

            addEvent();
        }

        function addEvent() {
            domBtn.addEventListener('click', send, false);
            domFile.addEventListener('change', send, false);
            ws.addEventListener('close', close, false);
            ws.addEventListener('error', error, false);
            ws.addEventListener('message', message, false);
            ws.addEventListener('open', open, false);
        }

        function send(event) {
            const files = event.target.files || [];
            const file = files[0]
            const message = domInput.value.trim();

            if (file) {
                const reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload = (event) => {
                    const params = JSON.stringify({
                        message: event.target.result,
                        dateTime: new Date().toLocaleString(),
                        username
                    })
                    ws.send(params);
                    domInput.value = '';
                }
            } else {
                const params = JSON.stringify({
                    message: message,
                    dateTime: new Date().toLocaleString(),
                    username
                })
                ws.send(params);
                domInput.value = '';
            }
        }

        function close() {
            console.log('client close');
        }

        function error() {
            console.log('client error');
        }

        function message(e) {
            const { message, dateTime, username } = JSON.parse(e.data);
            let messageElement;
            if (isBase64(message)) {
                messageElement = `<img src="${message}" class="margin-left-5" />`;
            } else {
                messageElement = `<span class="margin-left-5">${message}</span>`;
            }
            const liStr = `
                <li>
                    <div>${dateTime}</div>
                    <div class="flex-start-center">
                        <span>${username}:</span>
                        ${messageElement}
                    </div>
                </li>
            `;
            const domLi = document.createElement('li');
            domLi.innerHTML = liStr;
            domUl.appendChild(domLi);
        }

        function isBase64(str) {
            // if (str ==='' || str.trim() ===''){ return false; }
            // try {
            //     return btoa(atob(str)) == str;
            // } catch (err) {
            //     return false;
            // }
            return str.indexOf('data:image') > -1;
        }

        function open() {
            console.log('client open');
        }

        init();
    })();
</script>
</body>
</html>